"""Tests for sync_drive.py file."""

__author__ = "Mandar Patil (mandarons@pm.me)"

import os
import shutil
import time
import unittest
from pathlib import Path
from unittest.mock import MagicMock, patch
from urllib.parse import unquote

from icloudpy.exceptions import ICloudPyAPIResponseException

import tests
from src import LOGGER, read_config, sync_drive
from tests import DATA_DIR, data


class TestSyncDrive(unittest.TestCase):
    """Test class for sync_drive.py file."""

    def setUp(self) -> None:
        """Initialize tests."""
        self.config = read_config(config_path=tests.CONFIG_PATH)
        self.ignore = self.config["drive"]["ignore"]
        self.filters = self.config["drive"]["filters"]
        self.root = tests.DRIVE_DIR
        self.destination_path = self.root
        os.makedirs(self.destination_path, exist_ok=True)
        self.service = data.ICloudPyServiceMock(data.AUTHENTICATED_USER, data.VALID_PASSWORD)
        self.drive = self.service.drive
        self.items = self.drive.dir()
        self.folder_item = self.drive[self.items[5]]
        self.file_item = self.drive[self.items[4]]["Test"]["Scanned document 1.pdf"]
        self.package_item = self.drive[self.items[6]]["Sample"]["Project.band"]
        self.special_chars_package_item = self.drive[self.items[6]]["Sample"]["Fotoksiążka-Wzór.xmcf"]
        self.package_item_nested = self.drive[self.items[6]]["Sample"]["ms.band"]
        self.file_name = "Scanned document 1.pdf"
        self.package_name = "Project.band"
        self.package_name_nested = "ms.band"
        self.local_file_path = os.path.join(self.destination_path, self.file_name)
        self.local_package_path = os.path.join(self.destination_path, self.package_name)

    def tearDown(self) -> None:
        """Delete temp directory."""
        shutil.rmtree(tests.TEMP_DIR)

    def test_wanted_parent_folder_none_filters(self):
        """Test for wanted parent folder filters as None."""
        self.filters["folders"] = ["dir1/dir11"]
        self.assertTrue(
            sync_drive.wanted_parent_folder(
                filters=None,
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1/dir11"),
            ),
        )

    def test_wanted_parent_folder(self):
        """Test for a valid wanted parent folder."""
        self.filters["folders"] = ["dir1/dir11"]
        self.assertTrue(
            sync_drive.wanted_parent_folder(
                ignore=None,
                filters=self.filters["folders"],
                root=self.root,
                folder_path=os.path.join(self.root, "dir1/dir11/some/dirs/file.ext"),
            ),
        )

    def test_wanted_parent_folder_missing_parent_folder(self):
        """Test for missing parent folder."""
        self.filters["folders"] = ["dir1/dir11"]
        self.assertFalse(
            sync_drive.wanted_parent_folder(
                ignore=None,
                filters=self.filters["folders"],
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )

    def test_wanted_folder_single_variations(self):
        """Test for wanted folder variations."""
        self.filters["folders"] = ["dir1"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.filters["folders"] = ["/dir1"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.filters["folders"] = ["dir1/"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.filters["folders"] = ["/dir1/"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )

    def test_wanted_folder_single_path(self):
        """Test for wanted folder with single path."""
        self.filters["folders"] = ["dir1/dir2/dir3/", "dir1//dir2/dir3//"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir2"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir3"),
            ),
        )
        self.filters["folders"] = ["dir1//dir2/dir3//"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir2"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir3"),
            ),
        )

    def test_wanted_folder_multiple(self):
        """Test for multiple wanted folders."""
        self.filters["folders"] = ["dir1", "dir2"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir2"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir3"),
            ),
        )

    def test_wanted_folder_multiple_paths(self):
        """Test for wanted folder multiple paths."""
        self.filters["folders"] = ["dir1/dir2/dir3/", "dirA/dirB/dirC"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir2"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir3"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dirA"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dirA", "dirB"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dirA", "dirB", "dirC"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dirA", "dirC"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dirB"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters,
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dirC"),
            ),
        )

    def test_wanted_folder_ignore(self):
        """Tes for wanted folder ignore."""
        self.ignore = ["dir2/"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir2", "dir1"),
            ),
        )

    def test_wanted_folder_ignore_multiple_paths(self):
        """Test for wanted folder ignore multiple paths."""
        self.ignore = ["dir2/", "dir1/dir3/"]
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir4"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir2", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=None,
                ignore=["dir3"],
                root=self.root,
                folder_path=os.path.join(self.root, "dir1", "dir3"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=None,
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir2", "dir1"),
            ),
        )

    def test_wanted_folder_ignore_takes_precedence_to_filters(self):
        """Test for wanted folder ignore takes precedence to filters."""
        self.ignore = ["dir2/"]
        self.filters["folders"] = ["dir2/"]
        self.assertFalse(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=self.ignore,
                root=self.root,
                folder_path=os.path.join(self.root, "dir2", "dir3"),
            ),
        )

    def test_wanted_folder_empty(self):
        """Test for empty wanted folder."""
        original_filters = dict(self.filters)
        self.filters["folders"] = []
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=os.path.join(self.root, "dir1"),
            ),
        )
        self.filters = dict(original_filters)

    def test_wanted_folder_none_folder_path(self):
        """Test for wanted folder path as None."""
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
                folder_path=None,
            ),
        )

    def test_wanted_folder_none_filters(self):
        """Test for wanted folder filters as None."""
        self.assertTrue(sync_drive.wanted_folder(filters=None, ignore=None, root=self.root, folder_path="dir1"))

    def test_wanted_folder_none_root(self):
        """Test for wanted folder root as None."""
        self.assertTrue(
            sync_drive.wanted_folder(
                filters=self.filters["folders"],
                ignore=None,
                root=None,
                folder_path="dir1",
            ),
        )

    def test_wanted_file(self):
        """Test for a valid wanted file."""
        self.filters["file_extensions"] = ["py"]
        self.assertTrue(
            sync_drive.wanted_file(filters=self.filters["file_extensions"], ignore=None, file_path=__file__),
        )

    def test_wanted_file_missing(self):
        """Test for a missing wanted file."""
        self.assertFalse(
            sync_drive.wanted_file(
                filters=self.filters["file_extensions"],
                ignore=None,
                file_path=tests.CONFIG_PATH,
            ),
        )

    def test_wanted_file_check_log(self):
        """Test for valid unwanted file."""
        with self.assertLogs(logger=LOGGER, level="DEBUG") as captured:
            sync_drive.wanted_file(
                filters=self.filters["file_extensions"],
                ignore=None,
                file_path=tests.CONFIG_PATH,
            )
            self.assertTrue(len(captured.records) > 0)
            self.assertIn("Skipping the unwanted file", captured.records[0].getMessage())

    def test_wanted_file_none_file_path(self):
        """Test for unexpected wanted file path."""
        self.assertTrue(sync_drive.wanted_file(filters=None, ignore=None, file_path=__file__))
        self.assertFalse(sync_drive.wanted_file(filters=self.filters["file_extensions"], ignore=None, file_path=None))

    def test_wanted_file_empty_file_extensions(self):
        """Test for empty file extensions in wanted file."""
        original_filters = dict(self.filters)
        self.filters["file_extensions"] = []
        self.assertTrue(
            sync_drive.wanted_file(filters=self.filters["file_extensions"], ignore=None, file_path=__file__),
        )
        self.filters = dict(original_filters)

    def test_wanted_file_case_variations_extensions(self):
        """Test for wanted file extensions case variations."""
        self.filters["file_extensions"] = ["pY"]
        self.assertTrue(
            sync_drive.wanted_file(filters=self.filters["file_extensions"], ignore=None, file_path=__file__),
        )
        self.filters["file_extensions"] = ["pY"]
        self.assertTrue(
            sync_drive.wanted_file(
                filters=self.filters["file_extensions"],
                ignore=None,
                file_path=os.path.join(os.path.dirname(__file__), "file.Py"),
            ),
        )

    def test_wanted_file_ignore(self):
        """Test for wanted file exclude regex."""
        self.ignore = ["*.md", ".git/"]
        self.assertFalse(
            sync_drive.wanted_file(
                filters=None,
                ignore=self.ignore,
                file_path=os.path.join(self.root, "/dir1/README.md"),
            ),
        )
        self.assertFalse(
            sync_drive.wanted_file(
                filters=None,
                ignore=self.ignore,
                file_path=os.path.join(self.root, "/.git/index"),
            ),
        )
        self.assertTrue(
            sync_drive.wanted_file(
                filters=None,
                ignore=self.ignore,
                file_path=os.path.join(os.path.dirname(__file__), "/dir1/index.html"),
            ),
        )

    def test_wanted_file_ignore_takes_precedences_over_filters(self):
        """Test for wanted folder exclude regex."""
        self.ignore = ["*.py"]
        self.filters["file_extensions"] = ["py"]
        self.assertFalse(
            sync_drive.wanted_file(
                filters=self.filters["file_extensions"],
                ignore=self.ignore,
                file_path=os.path.join(self.root, "/dir1/index.py"),
            ),
        )

    def test_process_folder_wanted(self):
        """Test for valid wanted folder."""
        actual = sync_drive.process_folder(
            item=self.drive[self.items[0]],
            destination_path=self.destination_path,
            filters=self.filters["folders"],
            ignore=None,
            root=self.root,
        )
        self.assertIsNotNone(actual)
        self.assertTrue(os.path.exists(actual))
        self.assertTrue(os.path.isdir(actual))

    def test_process_folder_unwanted(self):
        """Test for valid unwanted folder."""
        actual = sync_drive.process_folder(
            item=self.drive[self.items[1]],
            destination_path=self.destination_path,
            filters=self.filters,
            ignore=None,
            root=self.root,
        )
        self.assertIsNone(actual)

    def test_process_folder_none_item(self):
        """Test for process folder item as None."""
        self.assertIsNone(
            sync_drive.process_folder(
                item=None,
                destination_path=self.destination_path,
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
            ),
        )

    def test_process_folder_none_destination_path(self):
        """Test for process folder destination path as None."""
        self.assertIsNone(
            sync_drive.process_folder(
                item=self.drive[self.items[1]],
                destination_path=None,
                filters=self.filters["folders"],
                ignore=None,
                root=self.root,
            ),
        )

    def test_process_folder_none_root(self):
        """Test for process folder root as None."""
        self.assertIsNone(
            sync_drive.process_folder(
                item=self.drive[self.items[1]],
                destination_path=self.destination_path,
                filters=self.filters["folders"],
                ignore=None,
                root=None,
            ),
        )

    def test_file_non_existing_file(self):
        """Test for file does not exist."""
        self.assertFalse(sync_drive.file_exists(item=self.file_item, local_file=self.local_file_path))

    def test_file_existing_file(self):
        """Test for file exists."""
        sync_drive.download_file(item=self.file_item, local_file=self.local_file_path)
        actual = sync_drive.file_exists(item=self.file_item, local_file=self.local_file_path)
        self.assertTrue(actual)
        # Verbose
        sync_drive.download_file(item=self.file_item, local_file=self.local_file_path)
        with self.assertLogs(logger=LOGGER, level="DEBUG") as captured:
            actual = sync_drive.file_exists(item=self.file_item, local_file=self.local_file_path)
            self.assertTrue(actual)
            self.assertTrue(len(captured.records) > 0)
            self.assertIn("No changes detected.", captured.records[0].getMessage())

    def test_file_exists_none_item(self):
        """Test if item is None."""
        self.assertFalse(sync_drive.file_exists(item=None, local_file=self.local_file_path))

    def test_file_exists_none_local_file(self):
        """Test if local_file is None."""
        self.assertFalse(sync_drive.file_exists(item=self.file_item, local_file=None))

    def test_download_file(self):
        """Test for valid file download."""
        self.assertTrue(sync_drive.download_file(item=self.file_item, local_file=self.local_file_path))

        # Verbose
        with self.assertLogs() as captured:
            self.assertTrue(sync_drive.download_file(item=self.file_item, local_file=self.local_file_path))
            self.assertTrue(len(captured.records) > 0)
            self.assertIn("Downloading ", captured.records[0].getMessage())

    def test_download_file_none_item(self):
        """Test for item as None."""
        self.assertFalse(sync_drive.download_file(item=None, local_file=self.local_file_path))

    def test_download_file_none_local_file(self):
        """Test for local_file as None."""
        self.assertFalse(sync_drive.download_file(item=self.file_item, local_file=None))

    def test_download_file_non_existing(self):
        """Test for non-existent local file download."""
        self.assertFalse(
            sync_drive.download_file(
                item=self.file_item,
                local_file=os.path.join(self.destination_path, "non-existent-folder", self.file_name),
            ),
        )

    def test_download_file_key_error_data_token(self):
        """Test for data token key error."""
        with patch.object(self.file_item, "open") as mock_item:
            mock_item.side_effect = KeyError("data_token")
            self.assertFalse(sync_drive.download_file(item=self.file_item, local_file=self.local_file_path))

    def test_download_file_object_not_found_exception(self):
        """Test for ObjectNotFoundException error handling."""
        with patch.object(self.file_item, "open") as mock_item:
            mock_item.side_effect = Exception("ObjectNotFoundException: Could not find document (NOT_FOUND)")
            self.assertFalse(sync_drive.download_file(item=self.file_item, local_file=self.local_file_path))

    def test_is_package_object_not_found_exception(self):
        """Test is_package function with ObjectNotFoundException error handling."""
        from src.drive_file_existence import is_package

        with patch.object(self.file_item, "open") as mock_item:
            mock_item.side_effect = Exception("ObjectNotFoundException: Could not find document (NOT_FOUND)")
            # Should return False when error occurs
            result = is_package(self.file_item)
            self.assertFalse(result)

    def test_process_file_non_existing(self):
        """Test for non-existing file."""
        files = set()
        # file does not exist
        self.assertTrue(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )
        self.assertTrue(len(files) == 1)

    def test_process_file_existing(self):
        """Test for existing file."""
        files = set()
        sync_drive.process_file(
            item=self.file_item,
            destination_path=self.destination_path,
            filters=self.filters["file_extensions"],
            ignore=None,
            files=files,
        )
        # file already exists but not changed
        self.assertFalse(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )

    def test_process_file_not_wanted(self):
        """Test for unwanted file."""
        files = set()
        self.assertFalse(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=self.destination_path,
                filters=self.filters,
                ignore=None,
                files=files,
            ),
        )

    def test_process_file_none_item(self):
        """Test for file item as None."""
        files = set()
        self.assertFalse(
            sync_drive.process_file(
                item=None,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )

    def test_process_file_none_destination_path(self):
        """Test for destination path as None."""
        files = set()
        self.assertFalse(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=None,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )

    def test_process_file_none_filters(self):
        """Test for filters as None."""
        files = set()
        self.assertTrue(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=self.destination_path,
                filters=None,
                ignore=None,
                files=files,
            ),
        )

    def test_process_file_none_files(self):
        """Test for files as None."""
        self.assertFalse(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=None,
            ),
        )

    def test_process_file_existing_file(self):
        """Test for existing file."""
        files = set()
        # Existing file
        sync_drive.download_file(item=self.file_item, local_file=self.local_file_path)
        self.assertFalse(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )
        # Locally modified file
        shutil.copyfile(
            os.path.join(tests.DATA_DIR, "thumb.jpeg"),
            os.path.join(self.destination_path, self.file_item.name),
        )
        self.assertTrue(
            sync_drive.process_file(
                item=self.file_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )

    def test_remove_obsolete_file(self):
        """Test for removing obsolete file."""
        obsolete_path = os.path.join(self.destination_path, "obsolete")
        os.mkdir(obsolete_path)
        obsolete_file_path = os.path.join(obsolete_path, os.path.basename(__file__))
        shutil.copyfile(__file__, obsolete_file_path)
        # Remove the file
        files = set()
        files.add(obsolete_path)
        actual = sync_drive.remove_obsolete(destination_path=self.destination_path, files=files)
        self.assertTrue(len(actual) == 1)
        self.assertFalse(os.path.isfile(obsolete_file_path))

    def test_remove_obsolete_directory(self):
        """Test for removing obsolete directory."""
        files = set()
        obsolete_path = os.path.join(self.destination_path, "obsolete")
        os.mkdir(obsolete_path)
        obsolete_file_path = os.path.join(obsolete_path, os.path.basename(__file__))
        shutil.copyfile(__file__, obsolete_file_path)
        files.add(obsolete_path)
        shutil.copyfile(__file__, obsolete_file_path)
        # Remove the directory
        files.remove(obsolete_path)
        actual = sync_drive.remove_obsolete(destination_path=self.destination_path, files=files)
        self.assertTrue(len(actual) == 1)
        self.assertFalse(os.path.isdir(obsolete_path))
        # Remove the directory with file
        os.mkdir(obsolete_path)
        shutil.copyfile(__file__, obsolete_file_path)
        actual = sync_drive.remove_obsolete(destination_path=self.destination_path, files=files)
        self.assertTrue(len(actual) > 0)
        self.assertFalse(os.path.isdir(obsolete_path))
        self.assertFalse(os.path.isfile(obsolete_file_path))
        # Verbose
        with self.assertLogs() as captured:
            os.mkdir(obsolete_path)
            shutil.copyfile(__file__, obsolete_file_path)
            actual = sync_drive.remove_obsolete(destination_path=self.destination_path, files=files)
            self.assertTrue(len(actual) > 0)
            self.assertFalse(os.path.isdir(obsolete_path))
            self.assertFalse(os.path.isfile(obsolete_file_path))
            self.assertTrue(len(captured.records) > 0)
            self.assertIn("Removing ", captured.records[0].getMessage())

    @patch(target="keyring.get_password", return_value=data.VALID_PASSWORD)
    @patch(target="src.config_parser.get_username", return_value=data.AUTHENTICATED_USER)
    @patch("icloudpy.ICloudPyService")
    @patch("src.read_config")
    def test_remove_obsolete_package(self, mock_read_config, mock_service, mock_get_username, mock_get_password):
        """Test for removing obsolete package."""
        mock_service = self.service
        config = self.config.copy()
        config["drive"]["remove_obsolete"] = True
        config["drive"]["destination"] = self.destination_path
        mock_read_config.return_value = config
        ms_band_package_local_path = os.path.join(self.destination_path, "Obsidian", "Sample", "ms.band")
        files = sync_drive.sync_drive(config=config, drive=mock_service.drive)
        self.assertIsNotNone(files)
        files.remove(ms_band_package_local_path)
        files = sync_drive.remove_obsolete(destination_path=self.destination_path, files=files)
        self.assertFalse(os.path.exists(ms_band_package_local_path))

    def test_remove_obsolete_none_destination_path(self):
        """Test for destination path as None."""
        self.assertTrue(len(sync_drive.remove_obsolete(destination_path=None, files=set())) == 0)

    def test_remove_obsolete_none_files(self):
        """Test for files as None."""
        obsolete_path = os.path.join(self.destination_path, "obsolete")
        self.assertTrue(len(sync_drive.remove_obsolete(destination_path=obsolete_path, files=None)) == 0)

    def test_sync_directory_without_remove(self):
        """Test for remove as False."""
        actual = sync_drive.sync_directory(
            drive=self.drive,
            destination_path=self.destination_path,
            root=self.root,
            items=self.drive.dir(),
            top=True,
            filters=self.filters,
            remove=False,
        )
        self.assertTrue(len(actual) == 49)
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy")))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy", "Test")))
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Document scanne 2.pdf")),
        )
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Scanned document 1.pdf")),
        )

    def test_sync_directory_with_remove(self):
        """Test for remove as True."""
        os.mkdir(os.path.join(self.destination_path, "obsolete"))
        shutil.copyfile(__file__, os.path.join(self.destination_path, "obsolete", "obsolete.py"))
        actual = sync_drive.sync_directory(
            drive=self.drive,
            destination_path=self.destination_path,
            root=self.root,
            items=self.drive.dir(),
            top=True,
            filters=self.filters,
            ignore=self.ignore,
            remove=True,
        )
        self.assertTrue(len(actual) == 49)
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy")))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy", "Test")))
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Document scanne 2.pdf")),
        )
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Scanned document 1.pdf")),
        )

    def test_sync_directory_without_folder_filter(self):
        """Test for no folder filter."""
        original_filters = dict(self.filters)
        del self.filters["folders"]
        actual = sync_drive.sync_directory(
            drive=self.drive,
            destination_path=self.destination_path,
            root=self.root,
            items=self.drive.dir(),
            top=True,
            filters=self.filters,
            ignore=self.ignore,
            remove=False,
        )
        self.assertTrue(len(actual) == 53)
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy")))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy", "Test")))
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Document scanne 2.pdf")),
        )
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Scanned document 1.pdf")),
        )
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "unwanted")))

        self.filters = dict(original_filters)

    def test_sync_directory_none_drive(self):
        """Test for drive as None."""
        self.assertTrue(
            len(
                sync_drive.sync_directory(
                    drive=None,
                    destination_path=self.destination_path,
                    root=self.root,
                    items=self.drive.dir(),
                    top=True,
                    filters=self.filters,
                    ignore=self.ignore,
                    remove=False,
                ),
            )
            == 0,
        )

    def test_sync_directory_none_destination(self):
        """Test for destination as None."""
        self.assertTrue(
            len(
                sync_drive.sync_directory(
                    drive=self.drive,
                    destination_path=None,
                    root=self.root,
                    items=self.drive.dir(),
                    top=True,
                    filters=self.filters,
                    ignore=self.ignore,
                    remove=False,
                ),
            )
            == 0,
        )

    def test_sync_directory_none_root(self):
        """Test for root as None."""
        self.assertTrue(
            len(
                sync_drive.sync_directory(
                    drive=self.drive,
                    destination_path=self.destination_path,
                    root=None,
                    items=self.drive.dir(),
                    top=True,
                    filters=self.filters,
                    ignore=self.ignore,
                    remove=False,
                ),
            )
            == 0,
        )

    def test_sync_directory_none_items(self):
        """Test for items as None."""
        self.assertTrue(
            len(
                sync_drive.sync_directory(
                    drive=self.drive,
                    destination_path=self.destination_path,
                    root=self.root,
                    items=None,
                    top=True,
                    filters=self.filters,
                    ignore=self.ignore,
                    remove=False,
                ),
            )
            == 0,
        )

    @patch(target="keyring.get_password", return_value=data.VALID_PASSWORD)
    @patch(target="src.config_parser.get_username", return_value=data.AUTHENTICATED_USER)
    @patch("icloudpy.ICloudPyService")
    @patch("src.read_config")
    def test_sync_drive_valids(self, mock_read_config, mock_service, mock_get_username, mock_get_password):
        """Test for valid sync_drive."""
        mock_service = self.service
        config = self.config.copy()
        config["drive"]["destination"] = self.destination_path
        mock_read_config.return_value = config
        self.assertIsNotNone(sync_drive.sync_drive(config=config, drive=mock_service.drive))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy")))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy", "Test")))
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Document scanne 2.pdf")),
        )
        self.assertTrue(
            os.path.isfile(os.path.join(self.destination_path, "icloudpy", "Test", "Scanned document 1.pdf")),
        )
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "Obsidian")))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "Obsidian", "Sample")))
        self.assertTrue(os.path.isfile(os.path.join(self.destination_path, "Obsidian", "Sample", "This is a title.md")))
        self.assertEqual(
            sum(
                f.stat().st_size
                for f in Path(os.path.join(self.destination_path, "Obsidian", "Sample", "Project.band")).glob("**/*")
                if f.is_file()
            ),
            sum(
                f.stat().st_size
                for f in Path(os.path.join(tests.DATA_DIR, "Project_original.band")).glob("**/*")
                if f.is_file()
            ),
        )

    def test_process_file_special_chars_package(self):
        """Test for special characters package."""
        files = set()
        # Download the package
        self.assertTrue(
            sync_drive.process_file(
                item=self.special_chars_package_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )

    def test_process_file_existing_package(self):
        """Test for existing package."""
        files = set()
        # Existing package
        sync_drive.download_file(item=self.package_item, local_file=self.local_package_path)
        # Do not download the package
        self.assertFalse(
            sync_drive.process_file(
                item=self.package_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )
        # Modify local package
        shutil.copyfile(
            os.path.join(tests.DATA_DIR, "thumb.jpeg"),
            os.path.join(self.local_package_path, self.file_item.name),
        )
        # Download the package
        self.assertTrue(
            sync_drive.process_file(
                item=self.package_item,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )

    def test_process_file_nested_package_extraction(self):
        """Test for nested package extraction."""
        files = set()
        self.assertTrue(
            sync_drive.process_file(
                item=self.package_item_nested,
                destination_path=self.destination_path,
                filters=self.filters["file_extensions"],
                ignore=None,
                files=files,
            ),
        )
        self.assertTrue(os.path.exists(os.path.join(self.destination_path, "ms.band")))

        self.assertEqual(
            sum(
                f.stat().st_size
                for f in Path(os.path.join(self.destination_path, "ms.band")).glob("**/*")
                if f.is_file()
            ),
            sum(f.stat().st_size for f in Path(os.path.join(tests.DATA_DIR, "ms.band")).glob("**/*") if f.is_file()),
        )

    def test_process_package_invalid_package_type(self):
        """Test for invalid package type."""
        self.assertFalse(sync_drive.process_package(local_file=os.path.join(DATA_DIR, "medium.jpeg")))

    def test_execution_continuation_on_icloudpy_exception(self):
        """Test for icloudpy exception."""
        with (
            patch.object(self.file_item, "open") as mocked_file_method,
            patch.object(
                self.folder_item,
                "dir",
            ) as mocked_folder_method,
        ):
            mocked_file_method.side_effect = mocked_folder_method.side_effect = ICloudPyAPIResponseException(
                "Exception occurred.",
            )
            filters = dict(self.filters)
            filters["folders"].append("unwanted")
            actual = sync_drive.sync_directory(
                drive=self.drive,
                destination_path=self.destination_path,
                root=self.root,
                items=self.drive.dir(),
                top=True,
                filters=filters,
                ignore=self.ignore,
                remove=False,
            )
            self.assertTrue(len(actual) == 50)
            self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy")))
            self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "icloudpy", "Test")))
            self.assertTrue(
                os.path.isfile(
                    os.path.join(
                        self.destination_path,
                        "icloudpy",
                        "Test",
                        "Document scanne 2.pdf",
                    ),
                ),
            )
            self.assertFalse(
                os.path.isfile(
                    os.path.join(
                        self.destination_path,
                        "icloudpy",
                        "Test",
                        "Scanned document 1.pdf",
                    ),
                ),
            )

    @patch(target="keyring.get_password", return_value=data.VALID_PASSWORD)
    @patch(target="src.config_parser.get_username", return_value=data.AUTHENTICATED_USER)
    @patch("icloudpy.ICloudPyService")
    @patch("src.read_config")
    def test_child_ignored_folder(self, mock_read_config, mock_service, mock_get_username, mock_get_password):
        """Test for child ignored folder."""
        mock_service = self.service
        config = self.config.copy()
        config["drive"]["destination"] = self.destination_path
        config["drive"]["ignore"] = ["icloudpy/*"]
        mock_read_config.return_value = config
        self.assertIsNotNone(sync_drive.sync_drive(config=config, drive=mock_service.drive))
        self.assertFalse(os.path.exists(os.path.join(self.destination_path, "icloudpy", "Test")))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "Obsidian")))
        self.assertTrue(os.path.isdir(os.path.join(self.destination_path, "Obsidian", "Sample")))
        self.assertTrue(os.path.isfile(os.path.join(self.destination_path, "Obsidian", "Sample", "This is a title.md")))
        self.assertEqual(
            sum(
                f.stat().st_size
                for f in Path(os.path.join(self.destination_path, "Obsidian", "Sample", "Project.band")).glob("**/*")
                if f.is_file()
            ),
            sum(
                f.stat().st_size
                for f in Path(os.path.join(tests.DATA_DIR, "Project_original.band")).glob("**/*")
                if f.is_file()
            ),
        )

    def test_get_max_threads(self):
        """Test that get_max_threads returns reasonable values."""
        config = read_config(config_path=tests.CONFIG_PATH)
        max_threads = sync_drive.get_max_threads(config)
        self.assertIsInstance(max_threads, int)
        self.assertGreater(max_threads, 0)
        self.assertLessEqual(max_threads, 8)

    def test_collect_file_for_download_valid_file(self):
        """Test collecting file for download - valid file."""
        files = set()
        download_info = sync_drive.collect_file_for_download(
            item=self.file_item,
            destination_path=self.destination_path,
            filters=self.filters["file_extensions"],
            ignore=self.ignore,
            files=files,
        )
        self.assertIsNotNone(download_info)
        self.assertEqual(download_info["item"], self.file_item)
        self.assertTrue(download_info["local_file"].endswith("Scanned document 1.pdf"))
        self.assertFalse(download_info["is_package"])
        self.assertIn(download_info["local_file"], files)

    def test_collect_file_for_download_unwanted_file(self):
        """Test collecting file for download - unwanted file."""
        files = set()
        # Use filter that doesn't match the PDF extension
        download_info = sync_drive.collect_file_for_download(
            item=self.file_item,
            destination_path=self.destination_path,
            filters=["jpg", "png"],  # This won't match PDF
            ignore=self.ignore,
            files=files,
        )
        self.assertIsNone(download_info)
        self.assertEqual(len(files), 0)

    def test_collect_file_for_download_existing_file(self):
        """Test collecting file for download - file already exists."""
        files = set()
        # Create the local file first
        local_file_path = os.path.join(self.destination_path, "Scanned document 1.pdf")
        os.makedirs(os.path.dirname(local_file_path), exist_ok=True)

        # Create file with same size as the item to trigger file_exists check (197334 bytes from mock data)
        with open(local_file_path, "wb") as f:
            f.write(b"A" * 197334)  # Match the size from the mock data

        # Set the modification time to match the item
        item_modified_time = time.mktime(self.file_item.date_modified.timetuple())
        os.utime(local_file_path, (item_modified_time, item_modified_time))

        download_info = sync_drive.collect_file_for_download(
            item=self.file_item,
            destination_path=self.destination_path,
            filters=self.filters["file_extensions"],
            ignore=self.ignore,
            files=files,
        )
        self.assertIsNone(download_info)  # Should be None since file exists

    def test_collect_file_for_download_package(self):
        """Test collecting file for download - package file."""
        files = set()
        download_info = sync_drive.collect_file_for_download(
            item=self.package_item,
            destination_path=self.destination_path,
            filters=self.filters["file_extensions"],
            ignore=self.ignore,
            files=files,
        )
        self.assertIsNotNone(download_info)
        self.assertEqual(download_info["item"], self.package_item)
        self.assertTrue(download_info["local_file"].endswith("Project.band"))
        self.assertTrue(download_info["is_package"])

    def test_download_file_task_success(self):
        """Test successful file download task."""
        files = set()
        download_info = {
            "item": self.file_item,
            "local_file": self.local_file_path,
            "is_package": False,
            "files": files,
        }

        result = sync_drive.download_file_task(download_info)
        self.assertTrue(result)
        self.assertTrue(os.path.exists(self.local_file_path))

    def test_download_file_task_failure(self):
        """Test failed file download task."""
        files = set()
        # Create invalid download info that will cause failure
        download_info = {
            "item": None,  # Invalid item
            "local_file": self.local_file_path,
            "is_package": False,
            "files": files,
        }

        result = sync_drive.download_file_task(download_info)
        self.assertFalse(result)

    @patch("src.sync_drive.get_max_threads")
    def test_sync_directory_parallel_downloads(self, mock_get_max_threads):
        """Test sync_directory with parallel downloads."""
        mock_get_max_threads.return_value = 2  # Use smaller thread pool for testing

        # Use a folder that contains multiple files
        test_folder = self.drive[self.items[4]]  # Test folder
        test_items = test_folder.dir()
        config = read_config(config_path=tests.CONFIG_PATH)

        # Modify filters to include the Test folder
        modified_filters = dict(self.filters)
        modified_filters["folders"] = ["Test"]  # Include Test folder specifically

        files = sync_drive.sync_directory(
            drive=test_folder,
            destination_path=self.destination_path,
            items=test_items,
            root=self.root,
            top=True,
            filters=modified_filters,
            ignore=self.ignore,
            remove=False,
            config=config,
        )

        self.assertIsInstance(files, set)
        # The test might not have files due to filtering, but we can still verify the function works
        mock_get_max_threads.assert_called()

    @patch("src.drive_sync_directory.collect_file_for_download")
    def test_sync_directory_exception_handling(self, mock_collect):
        """Test sync_directory exception handling when collect_file_for_download fails."""
        # Make collect_file_for_download raise an exception
        mock_collect.side_effect = Exception("Simulated error in collect_file_for_download")

        # This should not crash despite the exception
        files = sync_drive.sync_directory(
            drive=self.drive,
            destination_path=self.destination_path,
            root=self.root,
            items=self.drive.dir(),
            top=True,
            filters=self.filters,
            remove=False,
        )

        # Should return empty set since no files were processed due to exceptions
        self.assertIsInstance(files, set)
        # The function should continue processing despite exceptions
        mock_collect.assert_called()

    def test_thread_safe_file_operations(self):
        """Test that file set operations are thread-safe."""
        import threading
        import time

        files = set()
        results = []

        def add_files(start_num, count):
            for i in range(start_num, start_num + count):
                with sync_drive.files_lock:
                    files.add(f"file_{i}.txt")
                time.sleep(0.001)  # Small delay to increase chance of race conditions
            results.append(len(files))

        # Create multiple threads that add files concurrently
        threads = []
        thread_count = 3
        files_per_thread = 5
        for i in range(thread_count):
            thread = threading.Thread(target=add_files, args=(i * files_per_thread, files_per_thread))
            threads.append(thread)
            thread.start()

        # Wait for all threads to complete
        for thread in threads:
            thread.join()

        # Verify all files were added correctly
        expected_total = thread_count * files_per_thread
        self.assertEqual(len(files), expected_total)  # 3 threads × 5 files each

        # Verify all expected files are present
        for i in range(expected_total):
            self.assertIn(f"file_{i}.txt", files)

    def test_collect_file_for_download_invalid_params(self):
        """Test collect_file_for_download with invalid parameters."""
        files = set()

        # Test with None item
        result = sync_drive.collect_file_for_download(None, self.destination_path, None, None, files)
        self.assertIsNone(result)

        # Test with None destination_path
        result = sync_drive.collect_file_for_download(self.file_item, None, None, None, files)
        self.assertIsNone(result)

        # Test with None files
        result = sync_drive.collect_file_for_download(self.file_item, self.destination_path, None, None, None)
        self.assertIsNone(result)

    def test_download_file_task_exception(self):
        """Test download_file_task with exception handling."""
        # Create a mock download task that will cause an exception
        download_task = {
            "item": None,  # This will cause an exception
            "local_file": "/some/path/file.txt",
            "is_package": False,
            "files": set(),
        }

        result = sync_drive.download_file_task(download_task)
        self.assertFalse(result)  # Should return False on exception

    def test_parallel_vs_sequential_performance(self):
        """Test and verify parallel downloads provide performance improvement."""
        import time
        from unittest.mock import patch

        # Create mock download tasks that simulate time-consuming downloads
        def mock_slow_download(download_task):
            time.sleep(0.01)  # Simulate 10ms download time
            return True

        # Get directory items that we can actually use
        items = self.drive.dir()
        config = read_config(config_path=tests.CONFIG_PATH)

        # Test sequential downloads (max_threads=1)
        with (
            patch("src.config_parser.get_app_max_threads", return_value=1),
            patch("src.sync_drive.download_file_task", side_effect=mock_slow_download),
        ):
            start_time = time.time()
            sync_drive.sync_directory(
                drive=self.drive,
                destination_path=self.destination_path,
                items=items[:3],  # Use actual items from mock data
                root=self.root,
                top=True,
                filters=None,
                ignore=None,
                remove=False,
                config=config,
            )
            sequential_time = time.time() - start_time

        # Test parallel downloads (max_threads=4)
        with (
            patch("src.config_parser.get_app_max_threads", return_value=4),
            patch("src.sync_drive.download_file_task", side_effect=mock_slow_download),
        ):
            start_time = time.time()
            sync_drive.sync_directory(
                drive=self.drive,
                destination_path=self.destination_path,
                items=items[:3],  # Use actual items from mock data
                root=self.root,
                top=True,
                filters=None,
                ignore=None,
                remove=False,
                config=config,
            )
            parallel_time = time.time() - start_time

        # Verify parallel downloads are faster (with some tolerance for test variance)
        # Parallel should be at least 10% faster than sequential (lenient for CI)
        # Protect against division by zero or near-zero parallel_time
        epsilon = 1e-6
        if parallel_time < epsilon:
            improvement_ratio = 1.0
        else:
            improvement_ratio = sequential_time / parallel_time

        # Log the performance improvement for verification
        print("\nPerformance Test Results:")
        print(f"Sequential time: {sequential_time:.3f}s")
        print(f"Parallel time: {parallel_time:.3f}s")
        print(f"Performance improvement: {improvement_ratio:.2f}x faster")

        # Only assert if we have meaningful timing data
        if sequential_time > 0.001 and parallel_time > 0.001:
            self.assertGreaterEqual(
                improvement_ratio,
                0.9,  # Very lenient - just verify it's not significantly slower
                f"Parallel downloads ({parallel_time:.3f}s) should not be significantly slower than sequential ({sequential_time:.3f}s)",
            )

    @patch("src.drive_parallel_download.package_exists")
    def test_collect_file_for_download_package_exists(self, mock_package_exists):
        """Test collect_file_for_download when package already exists locally."""
        files = set()

        # Mock package_exists to return True so we can test the lines 259-262
        mock_package_exists.return_value = True

        # Use the existing package item from test setup
        package_item = self.package_item

        # Create the local package directory structure using the package name
        local_package_path = os.path.join(self.destination_path, self.package_name)
        os.makedirs(local_package_path, exist_ok=True)

        # Create some files inside the package to simulate existing package content
        test_file_path = os.path.join(local_package_path, "test_file.txt")
        subdir_path = os.path.join(local_package_path, "subdir")
        os.makedirs(subdir_path, exist_ok=True)
        test_file_path2 = os.path.join(subdir_path, "test_file2.txt")

        with open(test_file_path, "w") as f:
            f.write("test content")
        with open(test_file_path2, "w") as f:
            f.write("test content 2")

        download_info = sync_drive.collect_file_for_download(
            item=package_item,
            destination_path=self.destination_path,
            filters=None,
            ignore=None,
            files=files,
        )

        # Should return None since package exists, and files should be added to the set
        self.assertIsNone(download_info)
        # Verify that files from the package were added to the set (lines 259-262)
        self.assertIn(test_file_path, files)
        self.assertIn(test_file_path2, files)

    @patch("src.drive_parallel_download.download_file")
    def test_download_file_task_exception_handling(self, mock_download_file):
        """Test download_file_task when an exception occurs during download."""
        # Configure mock to raise an exception
        mock_download_file.side_effect = Exception("Test download error")

        task_info = {
            "item": self.file_item,
            "local_file": os.path.join(self.destination_path, "test_file.pdf"),
            "is_package": False,
            "files": set(),
        }

        # Call download_file_task which should catch the exception and return False
        result = sync_drive.download_file_task(task_info)

        # Should return False due to exception
        self.assertFalse(result)
        mock_download_file.assert_called_once()

    @patch("src.sync_drive.download_file_task")
    def test_parallel_download_future_exception(self, mock_download_task):
        """Test exception handling in parallel download result processing."""
        # Configure mock to raise an exception
        mock_download_task.side_effect = Exception("Test parallel download error")

        # Create some test files
        os.makedirs(self.destination_path, exist_ok=True)

        # Sync directory which will trigger parallel downloads
        files = sync_drive.sync_directory(
            drive=self.drive,
            destination_path=self.destination_path,
            items=self.items,
            root=self.root,
            config=None,
            filters=None,
            ignore=None,
        )

        # The function should complete despite exceptions
        self.assertIsInstance(files, set)

    @patch("src.sync_drive.download_file_task")
    @patch("src.sync_drive.get_max_threads")
    def test_parallel_download_returns_false(self, mock_get_max_threads, mock_download_task):
        """Test parallel download when download_file_task returns False."""
        # Configure mocks
        mock_get_max_threads.return_value = 2
        mock_download_task.return_value = False  # Simulate failed download

        config = read_config(config_path=tests.CONFIG_PATH)
        os.makedirs(self.destination_path, exist_ok=True)

        # Use items that will generate download tasks
        files = sync_drive.sync_directory(
            drive=self.drive,
            destination_path=self.destination_path,
            items=self.items,  # Use all items to ensure we get file downloads
            root=self.root,
            config=config,
            filters=None,
            ignore=None,
            remove=False,
        )

        # The function should complete and handle failures
        self.assertIsInstance(files, set)
        # Verify the download task was called (meaning parallel downloads ran)
        if mock_download_task.call_count > 0:
            # At least one download was attempted
            self.assertGreater(mock_download_task.call_count, 0)

    def test_download_file_returns_none_on_processing_failure(self):
        """Test download_file returns None when package processing fails."""
        import os
        from unittest.mock import MagicMock

        from src.drive_file_download import download_file

        # Use a package item that will trigger the package processing path
        local_file = os.path.join(self.destination_path, "test_package.band")

        # Mock the response object to have the packageDownload URL
        mock_response = MagicMock()
        mock_response.url = "https://p12-content.icloud.com/packageDownload?foo=bar"
        mock_response.iter_content.return_value = [b"test data"]
        mock_response.__enter__ = MagicMock(return_value=mock_response)
        mock_response.__exit__ = MagicMock(return_value=None)

        with (
            patch.object(self.package_item, "open", return_value=mock_response),
            patch("src.drive_package_processing.process_package", return_value=None),
        ):
            result = download_file(self.package_item, local_file)
            self.assertIsNone(result)

    def test_execute_parallel_downloads_empty_tasks(self):
        """Test execute_parallel_downloads with empty task list."""
        from src.drive_parallel_download import execute_parallel_downloads

        result = execute_parallel_downloads([], 4)
        self.assertEqual(result, (0, 0))

    @patch("src.drive_parallel_download.download_file_task")
    def test_parallel_download_exception_handling(self, mock_download_task):
        """Test parallel downloads handles exceptions properly."""
        from src.drive_parallel_download import execute_parallel_downloads

        # Make the download task raise an exception
        mock_download_task.side_effect = Exception("Download failed")

        # Create a simple download task
        download_tasks = [
            {
                "item": self.file_item,
                "destination_path": self.destination_path,
            },
        ]

        result = execute_parallel_downloads(download_tasks, 1)
        self.assertEqual(result, (0, 1))  # 0 successful, 1 failed

    @patch("src.drive_parallel_download.download_file_task")
    def test_parallel_download_false_result(self, mock_download_task):
        """Test parallel downloads handles False return values properly."""
        from src.drive_parallel_download import execute_parallel_downloads

        # Make the download task return False (indicating failure)
        mock_download_task.return_value = False

        # Create a simple download task
        download_tasks = [
            {
                "item": self.file_item,
                "destination_path": self.destination_path,
            },
        ]

        result = execute_parallel_downloads(download_tasks, 1)
        self.assertEqual(result, (0, 1))  # 0 successful, 1 failed

    def test_sync_directory_unwanted_parent_folder(self):
        """Test sync_directory skips files in unwanted parent folders."""
        from src.drive_sync_directory import _process_file_item

        # Create filters that specify a different folder (making current parent folder unwanted)
        restrictive_filters = {
            "folders": ["SomeOtherFolder/SubFolder"],  # Only allow a specific folder path that doesn't match our test
            "file_extensions": [],
        }

        files = set()
        download_tasks = []

        # Call _process_file_item directly with unwanted parent folder conditions
        _process_file_item(
            item=self.file_item,
            destination_path=self.destination_path,
            filters=restrictive_filters,
            ignore=self.ignore,
            root=self.root,
            files=files,
            download_tasks=download_tasks,
        )

        # Should have no download tasks since parent folder is not wanted
        self.assertEqual(len(download_tasks), 0)
        self.assertEqual(len(files), 0)

    def test_url_encoded_filename_decoding(self):
        """Test that URL-encoded filenames are properly decoded."""
        from src.drive_parallel_download import collect_file_for_download

        # Create a mock item with URL-encoded filename
        # This simulates files like "Geh.-Erhö+3,0+%+u.pdf" coming from iCloud as
        # "Geh.-Erho%CC%88+3%2C0+%25+u.pdf"
        url_encoded_filename = "Test-Erho%CC%88+3%2C0+%25+File.pdf"
        expected_decoded_filename = unquote(url_encoded_filename)  # "Test-Erhö+3,0+%+File.pdf"

        mock_item = MagicMock()
        mock_item.name = url_encoded_filename
        mock_item.type = "file"
        mock_item.size = 1024
        mock_item.date_modified = MagicMock()
        mock_item.date_modified.timestamp.return_value = time.time()

        files = set()

        # Collect file for download
        download_info = collect_file_for_download(
            item=mock_item,
            destination_path=self.destination_path,
            filters=None,
            ignore=None,
            files=files,
        )

        # Verify the local file path has the decoded filename
        self.assertIsNotNone(download_info)
        expected_path = os.path.join(self.destination_path, expected_decoded_filename)
        # Normalize both paths for comparison (NFC normalization)
        import unicodedata
        expected_normalized = unicodedata.normalize("NFC", expected_path)
        actual_normalized = unicodedata.normalize("NFC", download_info["local_file"])
        self.assertEqual(actual_normalized, expected_normalized)

        # Verify the filename doesn't contain URL encoding artifacts
        self.assertNotIn("%CC%88", download_info["local_file"])
        self.assertNotIn("%2C", download_info["local_file"])
        self.assertNotIn("%25", download_info["local_file"])
